package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.utils.QueryWrapperHelper;
import com.example.demo.entity.common.PageParams;
import com.example.demo.entity.common.PageResult;
import com.example.demo.entity.common.AppResp;
import com.example.demo.utils.OrikaBeanMapper;
import com.example.demo.utils.BeanUtil;
import com.example.demo.mapper.DemoMapper;
import com.example.demo.entity.vo.DemoVO;
import com.example.demo.entity.po.Demo;
import com.example.demo.service.DemoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  Service 接口实现类
 * </p>
 *
 * @author javalaoniu
 * @since 2022-03-25
 */
@Service("demoServiceImpl4demo")
@Slf4j
public class DemoServiceImpl extends ServiceImpl<DemoMapper, Demo> implements DemoService {

    @Autowired
    private DemoMapper demoMapper;

    @Override
    public AppResp<PageResult<DemoVO>> page(PageParams<DemoVO> pageParams) {
        Demo demo = OrikaBeanMapper.map(pageParams.getEntityParams(), Demo.class);
        QueryWrapper<Demo> queryWrapper = new QueryWrapper<>();
        try {
            QueryWrapperHelper.getInstance().convert(demo, queryWrapper);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            log.error("分页查询参数转换错误", e);
        }

        IPage<Demo> params = new Page<>();
        params.setCurrent(pageParams.getPageNum());
        params.setSize(pageParams.getPageSize());

        IPage<Demo> pageResultTmp = demoMapper.selectPage(params, queryWrapper);
        List<DemoVO> demoVOs = OrikaBeanMapper.mapAsList(pageResultTmp.getRecords(), DemoVO.class);

        PageResult<DemoVO> pr = new PageResult<>();
        pr.setCurrent(pageResultTmp.getCurrent());
        pr.setPages(pageResultTmp.getPages());
        pr.setSize(pageResultTmp.getSize());
        pr.setTotal(pageResultTmp.getTotal());
        pr.setRecords(demoVOs);
        return AppResp.success(pr);
    }

    @Override
    public AppResp<DemoVO> queryById(Long demoId) {
        QueryWrapper<Demo> queryWrapper = new QueryWrapper<>();

        Demo demo = demoMapper.selectById(demoId);
        if (ObjectUtils.isEmpty(demo)) {
            return AppResp.error("您查询的记录不存在，操作失败");
        }

        DemoVO demoVO = OrikaBeanMapper.map(demo, DemoVO.class);
        return AppResp.success(demoVO);
    }

    @Override
    public AppResp<Void> add(DemoVO demoVO) {
        Demo demo = OrikaBeanMapper.map(demoVO, Demo.class);
        // TODO 如果插入前需要根据某个属性判断对象是否存在，请修改下面代码：
        /*
        List<Demo> coreDemos = demoMapper.selectList(new QueryWrapper<Demo>().lambda()
            .eq(Demo::getAccount, demo.getAccount()));
        if (!ObjectUtils.isEmpty(coreDemos)) {
            return AppResp.error("已存在[" + demo.getAccount() + "]记录，添加失败");
        }
        */
        demo.setDeleteFlag(false);
        demo.setCreateAt(LocalDateTime.now());
        demo.setCreateBy("admin");
        return demo.insert() ? AppResp.success() : AppResp.error("操作失败，请重试");
    }

    @Override
    public AppResp<Void> delById(Long demoId) {
        Demo demo = demoMapper.selectById(demoId);
        if (ObjectUtils.isEmpty(demo)) {
            return AppResp.error("删除的对象不存在，操作失败");
        }
        demo.setDeleteFlag(true);
        demo.setUpdateAt(LocalDateTime.now());
        // TODO 需要改为当前登录的人
        demo.setUpdateBy("admin");
        return demo.updateById() ? AppResp.success() : AppResp.error("操作失败，请重试");

        // 下面是真实删除的代码，可以根据需要放开
        /*
        int i = demoMapper.deleteById(demoId);
        return i > 0 ? AppResp.success() : AppResp.error("操作失败，没有该记录");
        */
    }

    @Override
    public AppResp<Void> modify(DemoVO demoVO) {
        Demo demo = OrikaBeanMapper.map(demoVO, Demo.class);

        Demo existDemo = demoMapper.selectById(demo.getTid());
        if (ObjectUtils.isEmpty(existDemo)) {
            return AppResp.error("不存在[" + demo.getTid() + "]记录，操作失败");
        }

        try {
            BeanUtil.merge(demo, existDemo);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return AppResp.error("操作失败，"+e.getMessage());
        }

        existDemo.setUpdateAt(LocalDateTime.now());
        existDemo.setUpdateBy("admin");
        return existDemo.updateById() ? AppResp.success() : AppResp.error("操作失败，请重试");
    }
}
